'use strict';

module.exports = (app) => {
  class CarouselService extends app.Service {
    async create() {
      const { app, ctx } = this;
      const { Carousel, Photo } = app.model.Tables.Shop;
      const dataObj = ctx.request.body;
      console.log('------');
      console.log(ctx.adminInfo, ctx.userInfo);
      try {
        dataObj.user_id = (ctx.adminInfo || ctx.userInfo).id;
        dataObj.project_id = ctx.adminInfo.project_id;

        dataObj.sort = dataObj.sort || 999;

        const carouselRes = await Carousel.create(dataObj);
        const photoRes = await Photo.update(
          {
            type: 3,
            point_id: carouselRes.dataValues.id,
          },
          {
            where: {
              id: dataObj.photo_id,
            },
          }
        );

        return carouselRes;
      } catch (error) {
        return error.message ? error.message : error;
      }
    }

    async index() {
      const { app, ctx } = this;
      const { Carousel, Photo, CarouselGrop } = app.model.Tables.Shop;
      const query = ctx.query;
      let where = {};
      /** 判断条件中添加site_id */
      if (query.site_id) {
        where.site_id = query.site_id;
      }
      /** 判断条件中添加项目id */
      const project_id =
        (query.project_id && query.project_id) ||
        (ctx.adminInfo && ctx.adminInfo.project_id) ||
        ctx.userInfo.project_id;
      where.project_id = project_id;
      try {
        const res = await Carousel.findAll({
          where,
          include: [
            {
              // 需要的字段
              // attributes: ["id", "path"],
              model: Photo,
              where: {
                type: 3,
              },
            },
          ],
          distinct: true,
        });

        return res;
      } catch (error) {
        return error.message ? error.message : error;
      }
    }
  }
  return CarouselService;
};
